<?php

use React\EventLoop\Factory;
use React\Socket\SocketServer;
use GuzzleHttp\Client;
use think\Db;

require_once __DIR__ . '/../vendor/autoload.php';

// 定义常量
if (!defined('ROOT_PATH')) {
    define('ROOT_PATH', __DIR__ . '/');
}
if (!defined('DS')) {
    define('DS', DIRECTORY_SEPARATOR);
}

$loop = React\EventLoop\Factory::create();
$server = new React\Socket\SocketServer('0.0.0.0:2090', [], $loop);

echo "TCP Server running at 0.0.0.0:2090\n";

$connection->on('data', function ($data) use ($connection) {
    echo "Raw data dump:\n";
    var_dump($data); // 输出数据的详细信息
});

$server->on('connection', function ($connection) {
    echo "New connection received\n";

    $connection->on('data', function ($data) use ($connection) {
        
        print_r($data);
        
        echo "Raw data length: " . strlen($data) . "\n";
        echo "Raw data: " . bin2hex($data) . "\n";

        // 检测编码并转换
        $detectedEncoding = mb_detect_encoding($data, ['UTF-8', 'GBK', 'ISO-8859-1', 'ASCII'], true);
        if ($detectedEncoding) {
            $data = mb_convert_encoding($data, 'UTF-8', $detectedEncoding);
        } else {
            echo "Failed to detect encoding\n";
        }

        echo "Received data: $data\n";

        // 请求接口获取数据
        $responseFromAPI = getResponseFromAPI($data);
        echo "API Response: $responseFromAPI\n";

        $connection->write($responseFromAPI);
    });

    $connection->on('close', function () {
        echo "Connection closed\n";
    });
});


// 从接口获取数据
function getResponseFromAPI($data)
{
    
    print_r($data);
    //获取到的设备id
    
    $type = Db::name('xyvenue_device')->where('machine_id',$data['id'])->value('type');
    
    if($type=='light'){
         $url = "https://wq.hoeagri.com/api/xyvenue/Machine/setLight";
    }else if($type='air'){
         $url = "https://wq.hoeagri.com/api/xyvenue/Machine/setAirconditioner";
    }else{
         $url = "https://wq.hoeagri.com/api/xyvenue/Machine/setLight";
    }
    
    // $url = "https://wq.hoeagri.com/api/xyvenue/Machine/setEntranceGuard";
    $postData = json_encode([
        "id" => $data['id'] ?? '',
        "msg" => $data['msg'] ?? '',
        "switch" => $data['switch'] ?? 'off'
    ], JSON_UNESCAPED_UNICODE);

    $options = [
        'http' => [
            'header'  => "Content-Type: application/json\r\nAccept: application/json\r\n",
            'method'  => 'POST',
            'content' => $postData,
        ],
    ];

    $context  = stream_context_create($options);

    // 发送请求并获取响应
    $response = @file_get_contents($url, false, $context);
    
    if ($response === FALSE) {
        return json_encode(['error' => 'Failed to fetch data from API'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }

    // 转换为 UTF-8
    $detectedEncoding = mb_detect_encoding($response, ['UTF-8', 'GBK', 'ISO-8859-1', 'ASCII'], true);
    $response = mb_convert_encoding($response, 'UTF-8', $detectedEncoding);

    return $response;
}

// 启动事件循环
$loop->run();
